/**
 * @author jvillave
 */
var status_div_class = 'fixed_position';
var show_msg = '<img src="../resources/images/plus-icon.png"> Show ';
var hide_msg = '<img src="../resources/images/delete-icon.png"> Hide ';

var error_callback_function = function(){
		JSDAS.Demo.setStatus('Something went wrong', false, status_div_class);
}

var loading_message = function(msg){
	return 'Loading '+msg+'... <img src="../resources/images/wait.gif" />';
}

var  toggleDiv = function(divid){
    if(document.getElementById(divid).style.display == 'none'){
      document.getElementById(divid).style.display = 'block';
    }else{
      document.getElementById(divid).style.display = 'none';
    }
}

var changeMsg=function(div){
	if(div.innerHTML == hide_msg){
		div.innerHTML = show_msg;
	}else{
		div.innerHTML = hide_msg;
	}
}

var simpleListMaker = function(iteratable_obj, props, include_param_name){
	var i=0, l=iteratable_obj.length, list='<ul>';
	while(i<l){
		var current_obj = iteratable_obj[i], j=0, m= props.length;
		while(j<m){
			var format_props = '<li>';
			(include_param_name)?(format_props+=props[j]+": "+current_obj[props[j]]+" "):(format_props+= current_obj[props[j]]);
			format_props += '</li>';
			list+=format_props;
			j++;
		}
		i++;
	}
	list += '</ul>';
	return list;
}

var getSources = function(url, capability, authority, type, organism, label){
	JSDAS.Demo.setStatus(loading_message('Sources'), false, status_div_class);
	var client = JSDAS.Simple.getClient(url);
	
	var params = { 
			capability: capability,
			authority: authority,
			type: type,
			organism: organism,
			label: label
				
	};
	
	var callback_function = function(res){
			var sources_div = document.getElementById('sources_results');
			
			var sources = res.SOURCE;
			
			var response_str="<br/><div style='cursor:pointer' onclick='toggleDiv(\"soures\"), changeMsg(this);'>"+hide_msg+"</div><div id='soures'>";
			response_str += '<table class="results" width= "100%">';
			response_str += '<thead><tr><th>Title</th><th>Maintainer</th><th>Doc_href</th><th>Capabilities</th><th>Props</th></tr></thead>';
				
			var i=0, l=sources.length;
			while( i<l) {
				
				response_str += '<tbody>';
				
				var s = sources[i];
			    response_str += '<tr>';
			    response_str += '<td style="cursor:help" title="'+(s.description || 'No description available')+'">'+(s.title || '-')+'</td>';
			    response_str += '<td>'+('<a href="mailto:'+s.MAINTAINER.email+'">'+s.MAINTAINER.email+'</a>' || '-')+'</td>';
				response_str += '<td>'+(s.doc_href || '-')+'</td>';
			    
				var versions = s.VERSION, j=0, k=versions.length;
				var capabilities_html = "<td><div style='cursor:pointer' onclick='toggleDiv(1"+i+"), changeMsg(this);'>"+show_msg+"</div><div style='display:none' id='1"+i+"'><ul>";
				var props_html = "<td><div style='cursor:pointer' onclick='toggleDiv(2"+i+"), changeMsg(this);'>"+show_msg+"</div><div style='display:none' id='2"+i+"'><ul>";
				while (j < k) {
					
					capabilities_html += '<li>Version uri '+versions[j].uri;//+'</li>';
					var capabilities = versions[j].CAPABILITY;
					capabilities_html += simpleListMaker(capabilities, ['type'], false)+'</li>';
					
					props_html += '<li>Version uri '+versions[j].uri;//+'</li>';
					var props = versions[j].PROP;
					props_html += simpleListMaker(props, ['name', 'value'], false)+'</li>';
					j++;
				}
				capabilities_html += '</ul>';
				capabilities_html += '</div></td>';
				
				props_html += '</ul>';
				props_html += '</div></td>';
				
				response_str += capabilities_html + props_html + '</tr></tbody>';
				i++; 
			}
			response_str += '</table></br></div>';
			sources_div.innerHTML = response_str;
			JSDAS.Demo.setStatus('Done', true, status_div_class);
			
	}
	client.sources(callback_function, error_callback_function, params);
}

var getSequence = function(url, entry_point, start, stop){
	JSDAS.Demo.setStatus(loading_message('Sequence'), false, status_div_class);
	var client = JSDAS.Simple.getClient(url);
	
	var segment = entry_point+':'+start+','+stop;//REF:start,stop
	var params = {segment: segment};
	
	var callback_function = function(res){
			var sequence_div = document.getElementById('sequence_results');
			
			if(res.SEQUENCE){
				var response_str="<br/><div onclick='toggleDiv(\"seqres\"), changeMsg(this);'>"+hide_msg+"</div><div id='seqres'>";
				response_str += '<p>SEQUENCE: '+res.SEQUENCE[0].textContent+'</p></div>';
				sequence_div.innerHTML = response_str;
				JSDAS.Demo.setStatus('Done', true, status_div_class);
			} else{
				JSDAS.Demo.setStatus('Bad response, Wrong URL?, No Sequence XML?', false, status_div_class);
			}
	}
	
	client.sequence(params, callback_function, error_callback_function);
}

var getFeaturesQuery = function(url, query){
	var client = JSDAS.Simple.getClient(url);
 	
 	var params = {query: query};
 	
 	var callback_function = function(res){
 		var query_div = document.getElementById('query_results');
 		var segments = res.GFF.SEGMENT || [];
 		
 		var html = '';
 		for(var i=0, l=segments.length; i<l; ++i) {
 			var segment = segments[i];
 			html += '<fieldset><legend>Segment '+(segment.id || ' ')+'</legend>';
 			html += '<table class="results" width= "100%">';
			html += '<thead><tr><th>Id</th><th>Type</th><th>Method</th><th>Start</th><th>End</th><th>Score</th><th>Orientation</th><th>Link</th></tr></thead>';
			html += '<tbody>';
 			
 			var features = segment.FEATURE;
 			for(var j=0, k=features.length; j<k; ++j) {
			    var f = features[j];
			    html += '<tr>';
			    html += '<td>'+((f.label)?f.label+'<br>':'')+f.id+'</td>';
			    html += '<td>'+(f.TYPE.textContent || f.TYPE.id || '')+'</td>';
			    html += '<td>'+(f.METHOD.textContent || f.METHOD.id || '')+'</td>';
			    html += '<td>'+((f.START)?f.START.textContent:'')+'</td>';
			    html += '<td>'+((f.END)?f.END.textContent:'')+'</td>';
			    html += '<td>'+((f.SCORE)?f.SCORE.textContent:'')+'</td>';
			    html += '<td>'+((f.ORIENTATION)?f.ORIENTATION.textContent:'')+'</td>';
				    
				if(f.LINK && f.LINK[0] && f.LINK[0].href) { //Use only the first available link
			      html += '<td><a href="'+f.LINK[0].href+'">'+(f.LINK[0].textContent || f.LINK[0].href)+'</a></td>';
			    } else {
			      html += '<td></td>';
			    }
			    html +='</tr>';
			}
			html += '</tbody>';
			html += '</table>';
 			html += '</fieldset>';
 		}
 		
 		query_div.innerHTML = "<br/><div onclick='toggleDiv(\"quer\"), changeMsg(this);'>"+hide_msg+"</div><div id='quer'>"+html+"</div>";
		JSDAS.Demo.setStatus('Done', true, status_div_class);
 	}
 	
 	client.features(params, callback_function, error_callback_function);
}

var getFeatures = function(url, entry_point, start, stop){
	JSDAS.Demo.setStatus(loading_message('Features'), false, status_div_class);
	var client = JSDAS.Simple.getClient(url);
	
	var segment = entry_point+':'+start+','+stop;//REF:start,stop
	var params = {segment: segment};
	
	var callback_function = function(res){
			var features_div = document.getElementById('features_results');
			//write the sequence
			
			var features = res.GFF.SEGMENT[0].FEATURE;
			if (features){
				var table = '<table class="results" width= "100%">';
				table += '<thead><tr><th>Id</th><th>Type</th><th>Method</th><th>Start</th><th>End</th><th>Score</th><th>Orientation</th><th>Link</th></tr></thead>';
				table += '<tbody>';
				for(var i=0, l=features.length; i<l; ++i) {
				    var f = features[i];
				    table += '<tr>';
				    table += '<td>'+((f.label)?f.label+'<br>':'')+f.id+'</td>';
				    table += '<td>'+(f.TYPE.textContent || f.TYPE.id || '')+'</td>';
				    table += '<td>'+(f.METHOD.textContent || f.METHOD.id || '')+'</td>';
				    table += '<td>'+((f.START)?f.START.textContent:'')+'</td>';
				    table += '<td>'+((f.END)?f.END.textContent:'')+'</td>';
				    table += '<td>'+((f.SCORE)?f.SCORE.textContent:'')+'</td>';
				    table += '<td>'+((f.ORIENTATION)?f.ORIENTATION.textContent:'')+'</td>';
				    
					if(f.LINK && f.LINK[0] && f.LINK[0].href) { //Use only the first available link
				      table += '<td><a href="'+f.LINK[0].href+'">'+(f.LINK[0].textContent || f.LINK[0].href)+'</a></td>';
				    } else {
				      table += '<td></td>';
				    }
				    table +='</tr>';
				}
				table += '</tbody>';
				table += '</table>';
			
				features_div.innerHTML = "<br/><div onclick='toggleDiv(\"feares\"), changeMsg(this);'>"+hide_msg+"</div><div id='feares'>"+table+"</div>";
				JSDAS.Demo.setStatus('Done', true, status_div_class);
			}else{
				JSDAS.Demo.setStatus('Bad response, Wrong URL?, No Fetures XML?', false, status_div_class);
			}
	}
	
	client.features(params, callback_function, error_callback_function);
}

var getEntryPoints = function(url, start, stop){
	JSDAS.Demo.setStatus(loading_message('Entry points'), false, status_div_class);
	var client = JSDAS.Simple.getClient(url);
	
	var rows ="";
    if(start && stop) rows = start+'-'+stop;
	var params = {rows: rows};
	
	var callback_function = function(res){
			var entry_points_div = document.getElementById('entry_points_results');
			//write the sequence
			var entry_points = res.ENTRY_POINTS.SEGMENT;
			
			if(entry_points){
				var table = '<table class="results" width= "100%">';
				table += '<thead><tr><th>Id</th><th>Type</th><th>Start</th><th>Stop</th><th>Orientation</th><th>Subparts</th></tr></thead>';
				table += '<tbody>';
				for(var i=0, l=entry_points.length; i<l; ++i) {
				    var f = entry_points[i];
				    table += '<tr>';
				    table += '<td>'+(f.id || '')+'</td>';
				    table += '<td>'+(f.type || '')+'</td>';
				    table += '<td>'+(f.start || '')+'</td>';
				    table += '<td>'+(f.stop || '')+'</td>';
				    table += '<td>'+(f.orientation || '')+'</td>';
				    table += '<td>'+(f.subparts || '')+'</td>';
				    table +='</tr>';
				}
				table += '</tbody>';
				table += '</table>';
				
				entry_points_div.innerHTML = "<br/><div onclick='toggleDiv(\"entres\"), changeMsg(this);'>"+hide_msg+"</div><div id='entres'>"+table+"</div>";
				JSDAS.Demo.setStatus('Done', true, status_div_class);
			}else{
				JSDAS.Demo.setStatus('Bad response, Wrong URL?, No Entry Points XML?', false, status_div_class);
			}	
	}
	
	client.entry_points(params, callback_function, error_callback_function);
}

var getTypes = function(url, entry_point, start, stop){
	JSDAS.Demo.setStatus(loading_message('Types'), false, status_div_class);
	var client = JSDAS.Simple.getClient(url);
	
	var segment ="";
    if(start && stop && entry_point) segment = entry_point+':'+start+','+stop;
	var params = {segment: segment}
	
	var callback_function = function(res){
			var types_div = document.getElementById('types_results');
			
			var segments = res.GFF.SEGMENT;
			
			if(segments){
				var string_res = '';
			
				for (var i = 0, l = segments.length; i < l; ++i) {
					var segment = segments[i];
					
					string_res += '<table class="results" width= "100%"><thead><tr><th>ID</th><th>Start</th><th>Stop</th><th>Version</th><th>Label</th></tr></thead><tbody><tr><td>'+(segment.id || '')+'</td><td>'+(segment.start || '')+'</td><td>'+(segment.stop || '')+'</td><td>'+(segment.version || '')+'</td><td>'+(segment.label || '')+'</td></tr><tbody></table>'
					string_res += '<br/>';
					
					var types = segment.TYPE;
					
					string_res += '<table class="results" width= "100%"><thead><tr><th>ID</th><th>Cvid</th><th>Category</th><th>Text</th></tr></thead><tbody>';
					for (var j = 0, k = types.length; j < k; ++j) {
						
						
						var type = types[j];
						string_res +='<tr><td>'+(type.id || '')+'</td><td>'+(type.cvid || '')+'</td><td>'+(type.category || '')+'</td><td>'+(type.textContent || '')+'</td></tr>';
						
					}
					string_res += '</tbody></table>';
				}
				types_div.innerHTML = "<br/><div onclick='toggleDiv(\"typres\"), changeMsg(this);'>"+hide_msg+"</div><div id='typres'>"+string_res+"</div>";
				JSDAS.Demo.setStatus('Done', true, status_div_class);
			}else{
				JSDAS.Demo.setStatus('Bad response, Wrong URL?, No Types XML?', false, status_div_class);
			}
	}
	
	client.types(params, callback_function, error_callback_function);
}

var getStylesheet = function(url){
	var client = JSDAS.Simple.getClient(url);
	
	client.stylesheet(undefined, undefined);
}

var getAlignment = function(url){
	var client = JSDAS.Simple.getClient(url);
	//view-source:http://www.rcsb.org/pdb/rest/das/pdb_uniprot_mapping/alignment?query=4hhb
	client.alignment('4hhb',undefined, undefined);
}

var getURL = function(){
	var params1 = {
		segment: ['mt','X:1,1000', '1:50,200'],
		another: ['another','an1','an2'],
		nothing: '',
		features: 'feature'
	}
	
	var url = JSDAS.URL.paramsURLEncode(params1);
	alert(url);
}
